package br.com.diego.system.view.action;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperPrint;

public class JasperJsfUtils {
    
    public static void exportToPdf(JasperPrint jasperPrint, String filename) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = 
        (HttpServletResponse)facesContext.getExternalContext().getResponse();
        
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", 
                String.format("inline;filename=%s-%d.pdf",
                filename, new Date().getTime())
        );
        try {
            try {
                JasperExportManager.exportReportToPdfStream(
                        jasperPrint, response.getOutputStream());
            } catch (IOException ex) {
                Logger.getLogger(JasperJsfUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (JRException ex) {
            Logger.getLogger(JasperJsfUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        facesContext.responseComplete();
    }
    
}
